package com.cenwangkeji.resident.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.cenwangkeji.resident.R;
import com.cenwangkeji.resident.model.Constant;
import com.cenwangkeji.resident.model.OkHttpUtils;
import com.cenwangkeji.resident.model.bean.ImgBean;
import com.cenwangkeji.resident.model.bean.QuestionDetailBean;
import com.cenwangkeji.resident.model.bean.SuccessBean;
import com.cenwangkeji.resident.model.bean.User;
import com.cenwangkeji.resident.presenter.activity.QuestionDetailPresenter;
import com.cenwangkeji.resident.ui.adapter.QuestionDetailsAdapter;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.lws.basic.base.BaseActivity;
import com.lws.basic.persenter.ObserverOnNext;
import com.lws.basic.utils.common.MyLogger;
import com.lws.basic.utils.common.MyToast;
import com.lws.basic.utils.common.RxUtils;
import com.lws.basic.utils.common.UIUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TooManyListenersException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;

public class QuestionDetailActivity extends BaseActivity implements QuestionDetailPresenter.I {

    @BindView(R.id.srl)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.hd_recycleview)
    RecyclerView mHdRecycleview;
    @BindView(R.id.et_fieled_content)
    EditText mEtFieledContent; //要发送的内容
    @BindView(R.id.iv_addimg)   //图片发送
    ImageView mIv;
    @BindView(R.id.tv_name)
    TextView mTvDovtor;//医生名字
    @BindView(R.id.rl_fieledreport_ok)
    RelativeLayout mRlOk;
    private QuestionDetailPresenter mPresenter = new QuestionDetailPresenter(this);
    private int mId;
    private String mFilePath ="";
    private int mYxwyId;

    @Override
    public int setLayoutId() {
        return R.layout.activity_question_detail;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
    }

    @Override
    public void initData() {
        super.initData();
        ButterKnife.bind(this);
        UIUtils.adaptSoftInput(getWindow().getDecorView(), mRlOk);
        initRefresh();
        mId = getIntent().getIntExtra("date", 0);
        showLoading();
        mPresenter.getQuestion(mId);
    }


    @Override
    public void onQuestionSuccess(QuestionDetailBean bean) {
        if (bean.getMsg().equals(Constant.token_expired)) {
            signIn();
            finish();
        } else {
            if (bean.getData() != null) {
                mTvDovtor.setText("医生："+bean.getData().getUName());
                mYxwyId = bean.getData().getXywyId();
                mHdRecycleview.setLayoutManager(new LinearLayoutManager(this));
                mHdRecycleview.setAdapter(new QuestionDetailsAdapter(this
                        ,bean.getData().getWyjl(),bean.getData().getGsfUrl(),bean.getData().getUsfUrl()));
                mRefreshLayout.finishRefresh();
            } else {
                MyToast.show(bean.getMsg());
            }
        }
        dismissLoading();

    }

    @Override
    public void onSendSuccess(SuccessBean bean) {
        if (bean.getMsg().equals(Constant.token_expired)) {
            signIn();
            finish();
        } else {
            if (bean.getCode() ==0) {
                MyToast.show("发送成功");
                mPresenter.getQuestion(mId);

            } else {
                MyToast.show(bean.getMsg());
            }
        }
    }

    private void initRefresh(){
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                mPresenter.getQuestion(mId);
            }
        });
        mRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                mRefreshLayout.finishLoadmore();
            }
        });
    }

    @OnClick({R.id.iv_addimg,R.id.rl_fieledreport_ok})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_addimg:
                openPhoto();
                break;
            case R.id.rl_fieledreport_ok:
                String content= mEtFieledContent.getText().toString();
                if (TextUtils.isEmpty(content)){
                    MyToast.show("内容不能为空");
                }else {
                    mPresenter.send(mFilePath, content,mYxwyId);
                }
                break;
        }
    }

    //打开相册
    public void openPhoto() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .minSelectNum(1)
                .selectionMode(PictureConfig.SINGLE)
                .previewImage(true)
                .isCamera(true)
                .compress(true)
                .enableCrop(false)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    final List<LocalMedia> list = PictureSelector.obtainMultipleResult(data);
                    Glide.with(this).load(list.get(0).getCompressPath()).apply(new RequestOptions()
                            .error(R.mipmap.ic_task_add)).into(mIv);
                    mFilePath = list.get(0).getCompressPath();

            }
        }
    }

}
